<?php if(!defined('OCTOMS')){header('HTTP/1.1 403');die('{"error":"forbidden"}');}
/*
 * @package       OctoMS
 * @subpackage     DesignJotter
 * @link          http://designjotter.com
 * @copyright     Copyright 2012, Valentino-Jivko Radosavlevici
 * @license       GPL v3.0 (http://www.gnu.org/licenses/gpl-3.0.txt)
 * 
 * Redistributions of files must retain the above copyright notice.
 * 
 * @since         OctoMS 0.0.1, DesignJotter 2.0.1
 */
	
	/*
	 * Content wizard model
	 * 
	 * @package OctoMS.com
	 * @subpackage DesignJotter
	 * @link http://designjotter.com
	 * @license       GPL v3.0 (http://www.gnu.org/licenses/gpl-3.0.txt)
	 * @version 1.0
	 * 
	 * @author Valentino-Jivko Radosavlevici
	 */
	class w__content_m
	{
		// Received data
		var $data = null;
		
		// Functions array
		var $fnc = array();
		
		// Content array
		var $cnt = array();
		
		/**
		 * Set the functions to load for the AJAX response
		 * 
		 * @example 
		 * // Append function 'f'
		 * $this->_f('f');
		 * // Append 'true'
		 * $this->_f(true);
		 * // Append multiple values
		 * $this->_f(array('a','b'));
		 * // Return appended data
		 * $this->_f();
		 * 
		 * @param mixed $data
		 * @return $this/array
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function _f($data=null)
		{
			// Sanitize the input
			if (!is_null($data))
			{
				// Make sure this is an array
				if (!is_array($data))
				{
					$data = func_get_args();
				}
				
				// Cleanup the array
				$res = array();
				foreach ($data AS $key=>$value)
				{
					$value = strval($value);
					if (strlen($value)>0)
					{
						$res[] = $value;
					}
				}
				$data = $res;
				
				// Also the $fnc variable must be an array
				if (!is_array($this->fnc)) $this->fnc = array();
				
				// Merge the values
				$this->fnc = array_merge($this->fnc,$data);
				
				// Return this
				return $this;
			}
			else 
			{
				return $this->fnc;
			}
			
		}// end function _f()
		
		/**
		 * Set the content
		 * 
		 * // Set a key
		 * $this->_c('foo','bar');
		 * // Get a key
		 * $this->_c('foo')
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function _c($key=null,$value=null)
		{
			if (!is_null($key))
			{
				if (!is_null($value))
				{
					$this->cnt[$key] = $value;
					return $this;
				}
				else 
				{
					return isset($this->cnt[$key])?$this->cnt[$key]:null;
				}
			}
			else
			{
				return $this->cnt;
			}
			
		}// end function _c()
		
		/**
		 * Show a post
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function get_post()
		{
			if (isset($this->data['id']) && is_numeric($this->data['id']))
			{
				// Get the post information
				$post = get_post($this->data['id']);
				
				// Set the title
				$this->_c('title',get_the_title($this->data['id']));
				
				// Set the id
				$this->_c('id',$this->data['id']);
				
				// Set the permalink
				$this->_c('url',get_permalink($this->data['id']));
				
				// Set the rating
				$rating = sprintf(
					'<div class="rating" for="%s" votes="%s" score="%s"><div class="social"><a class="addthis_button_compact" rel="nofollow" title="%s" url="%s" href="http://www.addthis.com/bookmark.php?v=250&amp;pubid=xa-50224385051f1c56">Add This</a></div>',
					$this->data['id'],
					(int)get_post_meta($this->data['id'],'#votes',true),
					($score = (float)get_post_meta($this->data['id'],'#score',true)),
					htmlspecialchars($this->_c('title'),ENT_QUOTES),
					$this->_c('url')
				);
				$rating .= '<div class="stars">';
				for ($i=1;$i<=5;$i++)
				{
					$rating .= '<div'.((round($score,0) >= $i)?' class="x"':'').'></div>';
				}
				$rating .= '</div></div>';
				$this->_c('rating',$rating);
		
				// Load the session object
				$session = octoms('session');
				
				// Activate the simplified page version
				$session->start()->flash_set('simplified',true);
				
				// Print the featured image
				if (has_post_thumbnail($this->data['id']))
				{
					$img = wp_get_attachment_image_src(
						get_post_thumbnail_id(
							$this->data['id']
						),
						'large'
					);
					$storyImageStyle = 'style="background-image:url(\''.$img[0].'\');background-position: top center; background-size:auto 100%;"';
				}
				else 
				{
					$storyImageStyle = '';
				}
				print '<div class="image" '.$storyImageStyle.'></div><div class="clearfix"></div>';
				
				// Print the date and author
				if(false != $subtitle = get_post_meta($this->data['id'],'#subtitle',true))
				{
					print sprintf('<blockquote>%s</blockquote>',$subtitle);
				}
				
				// Get the custom data
				if (false != $metadata = get_post_meta($this->data['id']))
				{
					print '<ul class="meta style4">';
					foreach($metadata AS $key => $meta)
					{
						if (strpos($key, '_')!==0 && $key != '#score' && $key != '#votes' && $key != '#subtitle')
						{
							print sprintf(
								'<li><b>%s</b>: %s</li>',
								$key,
								implode(', ', $meta)
							);
						}
					}
					print '</ul>';
				}
				
				// Print the tags
				if (false !== $posttags = get_the_tags($this->data['id'])) {
					print '<ul class="tags">';
					foreach($posttags as $tag)
					{
						print sprintf(
							'<li><a href="%s">%s</a></li>',
							get_tag_link($tag->term_id),
							$tag->name
						);
					}
					print '</ul>';
				}
			
				// Load the chromebox functionality
				$this->_f('chromebox');
				
				// Request message
				return '"'.$this->cnt['title'].'" loaded successfully.';
			}
			else
			{
				return array('Invalid request. Please refresh and try again.',false);
			}
		}// end function get_post()
		
		/**
		 * Rate a specific post
		 * 
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function rate_post()
		{
			if (isset($this->data['id']) && isset($this->data['vote']))
			{
				// Start the session
				$session = octoms('session')->start();
				
				// Get the available votes
				$votes = $session->get('votes');
				
				// The votes variable must hold an array
				if (is_null($votes)) $votes = array();
				
				// Get the post ID
				$id = $this->data['id'];
				
				// Has the user already voted?
				if (isset($votes[$id]))
				{
					return array('You have already rated this item '.$votes[$id].' stars.','info');
				}
				else 
				{
					// Sanitize the vote
					$v = intval($this->data['vote']);
					$v = $v<1 ? 1 :($v>5?5:$v);
					
					// Append the ID to the session
					$votes[$id] = $v;
					$session->set('votes',$votes);
					
					// Get the available votes and score
					$meta_votes = (int)get_post_meta($id,'#votes',true);
					$meta_score = (float)get_post_meta($id,'#score',true);
					
					// Update the score
					update_post_meta($id, '#score', $meta_score = round(($meta_score*$meta_votes+$v)/($meta_votes+1),2));
					
					// Update the votes
					update_post_meta($id, '#votes', $meta_votes+1);
					
					// Send the data
					$this->_c('id',$id);
					$this->_c('score',$meta_score);
					
					// Use the update tool
					$this->_f('rating_update');
					
					// Thank you
					return 'Thank you for rating this item '.$v.' stars!';
				}
			}
			else
			{
				return array('Invalid request. Please refresh and try again.',false);
			}
			
		}// end function rate_post()
		
		/**
		 * Get a specific page
		 * 
		 * @example 
		 * 
		 * @param 
		 * @return 
		 * 
		 * @author Valentino-Jivko Radosavlevici
		 */
		function get_page()
		{
			if (isset($this->data['page']) && isset($this->data['last']))
			{
				// Sanitize the page
				$this->data['page'] = intval($this->data['page']);
				if ($this->data['page']<1) $this->data['page'] = 1;
				
				// Sanitize the last box number
				$this->data['last'] = intval($this->data['last']);
				$this->data['last'] = ($this->data['last']<1)?1:($this->data['last']>14?14:$this->data['last']);

				// Get the query string
				global $query_string;
				
				// Already on a page?
				if (preg_match('/paged=[0-9]+/i', $query_string)) 
				{
					$query_string = preg_replace('/(paged=)[0-9]+/i', '${1}'.$this->data['page'], $query_string);
				}
				else
				{
					// Empty query string?
					if (strlen($query_string)==0)
					{
						$query_string = 'paged='.$this->data['page'];
					}
					else 
					{
						$query_string .= '&paged='.$this->data['page'];
					}
				}
				
				// Get the data
				$data = query_posts($query_string);
				
				// Any results?
				if (count($data)>0)
				{
					// Prepare the result
					$result = array();
					
					// Load the view object
					$view = octoms('view');
					
					// Get the box no
					$p = $this->data['last'];
					if ($p == 14) $p = 1;
					
					// Format the content
					foreach ($data AS $post)
					{
						// Use this as an Array
						$post = (array)$post;
						
						// Get the ID
						$result[$p] = $view->load('post',
							array(
								'id' => $post['ID'],
								'position' => $p
							)
						); 
						
						// Increment the position
						$p++;if($p>14)$p=1;
					}

					// Send the results
					$this->_c('posts',$result);
					
					// Confirm the current page
					$this->_c('page',$this->data['page']);
					
					// Success
					$this->_c('status','success');
					
					// Use the append page utility
					$this->_f('append_page');
					
					// All done!
					return 'Page '.$this->data['page'].' retrieved successfully!';
				}
				// Stop here
				else 
				{
					// Stop here
					$this->_c('status','stop');
					
					// Use the append page utility
					$this->_f('append_page');
					
					// All done
					return array('No more items to load.','info');
				}
			}
			else 
			{
				return array('Invalid request. Please refresh and try again.',false);
			}
		}// end function get_page()
		
	}// end class w__content_m
	
	
/* End Of File <_content.inc> */